package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.modbus.Modbus4jWriteUtils;
import com.ruoyi.system.domain.MrWard;
import com.ruoyi.system.mapper.MrWardMapper;
import com.ruoyi.system.service.IMrWardService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 病区Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-01
 */
@Service
public class MrWardServiceImpl implements IMrWardService {
    @Autowired
    private MrWardMapper mrWardMapper;

    @Autowired
    private ISysConfigService configService;

    /**
     * 查询病区
     *
     * @param wardId 病区主键
     * @return 病区
     */
    @Override
    public MrWard selectMrWardByWardId(Long wardId) {
        return mrWardMapper.selectMrWardByWardId(wardId);
    }

    /**
     * 查询病区列表
     *
     * @param mrWard 病区
     * @return 病区
     */
    @Override
    public List<MrWard> selectMrWardList(MrWard mrWard) {
        return mrWardMapper.selectMrWardList(mrWard);
    }

    /**
     * 新增病区
     *
     * @param mrWard 病区
     * @return 结果
     */
    @Override
    public int insertMrWard(MrWard mrWard) {
        mrWard.setCreateTime(DateUtils.getNowDate());
        int count = mrWardMapper.insertMrWard(mrWard);
        if (count > 0 && !mrWard.getFloor().isEmpty()) {
            String port = configService.selectConfigByKey(Constants.CONFIGURATION_PORT);
            port = port == null ? "9999" : port;
            try {
                Modbus4jWriteUtils.writeCoil(mrWard.getFloor(), Integer.parseInt(port), 1, 1, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return count;
    }

    /**
     * 修改病区
     *
     * @param mrWard 病区
     * @return 结果
     */
    @Override
    public int updateMrWard(MrWard mrWard) {
        mrWard.setUpdateTime(DateUtils.getNowDate());
        int count = mrWardMapper.updateMrWard(mrWard);
        if (count > 0 && !mrWard.getFloor().isEmpty()) {
            try {
                Modbus4jWriteUtils.writeCoil(mrWard.getFloor(), 9999, 1, 1, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    /**
     * 批量删除病区
     *
     * @param wardIds 需要删除的病区主键
     * @return 结果
     */
    @Override
    public int deleteMrWardByWardIds(Long[] wardIds) {
        return mrWardMapper.deleteMrWardByWardIds(wardIds);
    }

    /**
     * 删除病区信息
     *
     * @param wardId 病区主键
     * @return 结果
     */
    @Override
    public int deleteMrWardByWardId(Long wardId) {
        return mrWardMapper.deleteMrWardByWardId(wardId);
    }

    @Override
    public int checkDeptBandWard(Long[] deptIds) {
        return mrWardMapper.checkDeptBandWard(deptIds);
    }
}
